package com.ruoyi.youtian.task;

import com.ruoyi.common.config.thread.ThreadPoolConfig;
import com.ruoyi.common.constant.YouQiConstants;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.YouTianThreadPool;

import com.ruoyi.common.utils.html.ScriptEngineUtil;
import com.ruoyi.gzmx_tag_history.service.IGzmx_tag_historyService;
import com.ruoyi.youtian.domain.Template;
import com.ruoyi.youtian.domain.vo.TEarlyWarningVo;
import com.ruoyi.youtian.domain.vo.TemplateSceneVO;
import com.ruoyi.youtian.service.*;
import com.ruoyi.youtian.threadConfig.AsyncAnalyseEarlyWarning;
import com.ruoyi.youtian.threadConfig.AsyncAnalyseFault;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.util.JavaScriptUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @Author li long
 * @Date 2022/9/17
 * @Version V1.0.0
 * @Description 油田业务定时任务
 */
@Component("youTianTask")
@Slf4j
public class YouTianTask {


    @Autowired
    private  ITemplateService templateService;

    @Autowired
    private IFaultRecordService faultRecordService;


    @Autowired
    private ITemplateDetailService templateDetailService;


    /**
     * 预警值进行比较
     */
    @Autowired
    private ITEarlyWarningService itEarlyWarningService;

    /**
     * 点位历史记录值
     */
    @Autowired
    private IGzmx_tag_historyService gzmx_tag_historyService;

    @Autowired
    private ITEarlyWarningRecordService itEarlyWarningRecordService;
    @Autowired
    private ITEarlyWarningRecordDetailService itEarlyWarningRecordDetailService;




    /**
     *  sys_job表中 job_id 为 7
     *  功能描述:
     *
     *  2.判断头节点 如果有超过上限, 或者低于下限, 触发异常分析
     *  3.异常分析逻辑:
     *
     *
     */
    public void monitorScenePoint() {

        // 1.场景下 所有发布的模板, 找到模板下的头节点,(发布状态, 头节点, 未删除)
        TemplateSceneVO templateSceneVO = new TemplateSceneVO();
        templateSceneVO.setSourceTop(YouQiConstants.HEAD_NODE_TYPE);
        List<TemplateSceneVO> templateSceneVOList = templateService.selectSceneSourcePoint(templateSceneVO);
        log.info("templateSceneVOList: {}", LocalDateTime.now(), templateSceneVOList.size());
        //判断 异常头节点 , 大于上限 或者 小于下限 , 去重
        List<Long> templateIds = templateSceneVOList.stream()
                .filter(vo -> vo.getPointValue() != null && vo.getUpperLimit() != null && vo.getLowerLimit() != null)
                .filter(vo -> vo.getPointValue() > vo.getUpperLimit() || vo.getPointValue() < vo.getLowerLimit())
                .filter(vo -> Objects.equals(1, vo.getStatus()))
                //.filter(vo -> judgeOperation(vo))  // 根据自定义条件公式判断是否走这个模型进行分析
                .map(TemplateSceneVO::getTemplateId)
                .distinct()
                .collect(Collectors.toList());
        log.info("{}_异常的场景templateId为: {}", LocalDateTime.now(), templateIds);

        // 2.多线程去执行每个流程
        templateIds.forEach(id -> {
            //启动异常分析流程
            YouTianThreadPool.getPatrolPool().
                    execute(new AsyncAnalyseFault("异常分析,templateId: " + id, templateService, faultRecordService, templateDetailService, id));

        });
    }

    /**
     *
     * 判断自定义条件是否启用
     * 将目标点位的采集值和源点位的采集值带入公式计算
     * @param
     * @param vo 模板详情对象
     * @return
     */
    public boolean judgeOperation( TemplateSceneVO vo){
        String formulaTxt = vo.getFormulaText(); //formulaTxt 规则公式
        if (StringUtils.isNotEmpty(formulaTxt) && vo.getOperateRuleStatus() == 0 ){
            formulaTxt.replaceAll("\\{source_point_id}",vo.getPointValue()+"");
            formulaTxt.replaceAll("\\{target_point_id}",vo.getTargetValue().toString()+"");
        }
        return ScriptEngineUtil.eval(formulaTxt);
    }


    /**
     * 定时去监测
     */
    public void monitorEarlyWaringPoint(){
        TEarlyWarningVo earlyWarningVo = new TEarlyWarningVo();
        earlyWarningVo.setStatus("0");
        List<TEarlyWarningVo> tEarlyWarningVoList = itEarlyWarningService.selectEarlyWarningVoList(earlyWarningVo);
        tEarlyWarningVoList.forEach(tEarlyWarning -> {
            // 预警监控
            YouTianThreadPool.getPatrolPool().
                    execute( new AsyncAnalyseEarlyWarning("预警监控"+ tEarlyWarning.getWarningCode(), itEarlyWarningService,  gzmx_tag_historyService,  itEarlyWarningRecordService,
                            itEarlyWarningRecordDetailService ,  faultRecordService, tEarlyWarning));

        });
    }

}
